package com.apexsoft.test.sample.ams.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apex.ams.util.AasCommService;
import com.apexsoft.aas.service.model.*;
import com.apexsoft.test.sample.ams.consumer.AmsClientDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.HashMap;

@RestController
public class AmsClientController {

    @Autowired
    AmsClientDemo amsClientDemo;

    @RequestMapping("grpcSay")
    public JSONObject grpcSay() {
        return amsClientDemo.grpcSay();

    }

    @RequestMapping("test")
    public JSONObject test(@RequestParam String name) {
        ARequest request =  new ARequest();
        request.setParams(new HashMap<String,Object>(){{
            put("name",name);
        }});
        AResponse response = AasCommService.sendRequest("test", "abc.service1", request);
        return (JSONObject) JSON.toJSON(response);
    }

    @RequestMapping("download")
    public JSONObject donwnload() throws IOException {
        ADownloadRequest request =  new ADownloadRequest();
        request.setParams(new HashMap<String,Object>(){{
            put("filename","build.gradle");
        }});
        ADownloadResponse response = AasCommService.download("test", "download.service", request);
        File file = new File(response.getFileInfo().getFileName());
        if(!file.exists()){
            file.createNewFile();
        }
        try(FileOutputStream fos = new FileOutputStream(file);
            InputStream is = response.getInputStream(); ){
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            fos.write(bytes);
        }
        return (JSONObject) JSON.toJSON(response.getFileInfo());
    }

    @RequestMapping("upload")
    public JSONObject upload() throws IOException {
        AUploadRequest request =  new AUploadRequest();
        request.setFileInfo(new UploadFileInfo(){{
            setFileName("build.gradle");
        }});
        request.setInputStream(new FileInputStream("build.gradle"));
        AUploadResponse response = AasCommService.upload("test", "upload.service", request);
        return (JSONObject) JSON.toJSON(response);
    }
}
